import React, { useEffect, useState } from 'react';
import { Pie } from '@ant-design/plots';
import { PageContainer, ProCard } from '@ant-design/pro-components';
import { listTopInterfaceCallCondUsingGet } from '@/services/sutongapi-backend/userInterfaceInfoController';
import { listInterfaceMethodCondUsingGet } from '@/services/sutongapi-backend/interfaceInfoController';

// 字符串转数值
const strToNum = (arr: any, target: any) => {
  for (let i = 0; i < arr.length; i++) {
    for (const key in arr[i]) {
      if (key === target) {
        arr[i][key] = arr[i][key] * 1;
      }
    }
  }
};
const Analysis = () => {
  const [interfaceCallData, setInterfaceCallData] = useState<API.InterfaceCallAnalysisVo[]>();
  const [interfaceMethodData, setInterfaceMethodData] = useState<API.InterfaceMethodAnalysisVo[]>();

  const loadInterfaceCallData = async () => {
    const res = await listTopInterfaceCallCondUsingGet();
    strToNum(res.data, 'totalNum');
    setInterfaceCallData(res.data);
  };
  const loadInterfaceMethodData = async () => {
    const res = await listInterfaceMethodCondUsingGet();
    strToNum(res.data, 'totalNum');
    setInterfaceMethodData(res.data);
  };

  useEffect(() => {
    loadInterfaceCallData();
    loadInterfaceMethodData();
  }, []);

  const config1 = {
    data: interfaceCallData,
    forceFit: true,
    angleField: 'totalNum',
    colorField: 'name',
    radius: 0.8,
    label: {
      text: (d: API.InterfaceCallAnalysisVo) => `${d.name}`,
      position: 'spider',
    },
    legend: {
      color: {
        title: false,
        position: 'right',
        rowPadding: 5,
      },
    },
  };
  const config2 = {
    data: interfaceMethodData,
    forceFit: true,
    angleField: 'totalNum',
    colorField: 'method',
    radius: 0.8,
    label: {
      text: (d: API.InterfaceMethodAnalysisVo) => `${d.method}`,
      position: 'spider',
    },
    legend: {
      color: {
        title: false,
        position: 'right',
        rowPadding: 5,
      },
    },
  };
  return (
    <PageContainer>
      <ProCard>
        <ProCard title="调用次数TOP10">
          <Pie {...config1} />
        </ProCard>
        <ProCard title="接口调用方式占比">
          <Pie {...config2} />
        </ProCard>
      </ProCard>
    </PageContainer>
  );
};

// 文档：https://ant-design-charts.antgroup.com/examples
export default Analysis;
